package com.yan_jiu_sheng.LeetCodeHot100.AC;

/**
 * https://leetcode.cn/problems/swap-nodes-in-pairs/description/?envType=study-plan-v2&envId=top-100-liked
 * 通过
 *
 * @author yulongTian
 * @create 2024-05-30 15:39
 */
public class Test30 {
    public static void main(String[] args) {
        new Test30().method();
    }

    private void method() {
        ListNode head1 = new ListNode(1);
        ListNode head2 = new ListNode(2);
        ListNode head3 = new ListNode(3);
        ListNode head4 = new ListNode(4);
        head1.next = head2;
        head2.next = head3;
        head3.next = head4;
        ListNode listNode = swapPairs(head1);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }


    private class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    private ListNode swapPairs(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode p = head.next.next;
        ListNode resHead = head.next;
        resHead.next = head;
        ListNode resLastP = head;
        resLastP.next = null;
        while (true) {
            if (p == null) {
                break;
            }
            if (p.next == null) {
                resLastP.next = p;
                break;
            }
            ListNode t1 = p;
            ListNode t2 = p.next;
            p = p.next.next;
            resLastP.next = t2;
            t2.next = t1;
            resLastP = t1;
            resLastP.next = null;
        }
        return resHead;
    }

}
